/**
 * 接口封装
 * -200 表示用户不存在
 * -201 图书不存在
 * -202 章节不存在
 * -203 内容不存在
 * -204 余额不足
 * -205 标签不存在图书
 * -206 不存在标签
 * -207 没有关注公众号
 * -208 评论不存在
 * -209 手机号码格式不正确
 * -210 发送短信过频
 * -211/-212 用户没有登录
 * -215 章节未购买
 * -300/-400 参数错误
 * -505 api接口不再维护
 * 0 失败
 * 0 该包不详
 * 1 成功
 * 1 该包不详
 * 2 书卷香
 * 3 该包不详
 * 4 乐书小说
 * 401 token过期
 * 402 刷新token
 * 403 游客登录
 * 5 该包不详
 * 6 文悦小说
 * 7 有书云阅读
 * 8 小说快读
 * 9 掌上追书
 */
const prompt = require('@system.prompt')
const storage = require('@system.storage')
const fetch = require('@system.fetch')
const file = require('@system.file')

const device = require('@system.device')
const md5 = require('md5')
const router = require('@system.router')

function fn_device_get() {
  return new Promise((resolve) => {
    storage.get({
      key: 'device_info',
      success: function (val) {
        console.log('get===========val'+val)
        val === '' ? '' : val
        resolve(val)
      },
      fail: function (data, code) {
        console.log(`handling fail, code = ${code}`)
      }
    })
  })
}

function fn_device_oaid_get(){
  return new Promise((resolve) => {
    device.getOAID({
      success: function(data) {

        console.log('============================================'+JSON.stringify(data) )
        resolve(data.oaid)
      },
      fail: function(data, code) {
        console.log(`handling fail, code = ${code}`)
      }
    })
  })
  
}

function fn_device_getID(_this) {
  if(_this != ''){
    _this.is_call = false
  }
  return new Promise((resolve) => {
    device.getId({
      type: ['device', 'mac', 'user'],
      success: function (data) {
        fn_device_set(data)
        resolve(data)
        // prompt.showDialog({
        //   message:'device.getId设备获取 ======= ' +JSON.stringify(data),
        //   buttons:[{
        //     text:"确定"
        //   }]
        // })
      },
      fail: function (data, code) {
        fn_device_set('{}') // 当拒绝时，本地存字符串{} 为了，不重复唤起授权弹窗（缓存为空时，会重复获取授权）
        resolve(data)
        console.log(`handling fail, code = ${code}`)
      }
    })
  });
}
function fn_device_set(value) {
  return new Promise((resolve) => {
    storage.set({
      key: 'device_info',
      value: value,
      success: function (data) {
        resolve('存储成功')
      },
      fail: function (data, code) {
        console.log(`handling fail, code = ${code}`)
      }
    })
  });
}

function getToken() {
  return new Promise((resolve) => {
    storage.get({
      key: 'token',
      success: function (tkn) {
        resolve(tkn)
      },
      fail: function (data, code) {
        console.log(`handling fail, code = ${code}`)
      }
    })
  });
}
function setToken(token) {
  return new Promise((resolve) => {
    storage.set({
      key: 'token',
      value: token,
      success: function (data) {
        resolve('存储成功')
      },
      fail: function (data, code) {
        console.log(`handling fail, code = ${code}`)
      }
    })
  });
}


function getKey() {
  return new Promise((resolve) => {
    storage.get({
      key: "key",
      success: function (res) {
        resolve(res)
      },
      fail: function (res) {
        console.log(res)
      }
    })
  })
}

function getDevice() {
  return new Promise((resolve) => {
    device.getInfo({
      success: function (ret) {
        resolve(ret)
      }
    })
  })
}

async function api( _this ,url, data = {}, header = {}) {
  // http://devapi.ad6755.com
  // http://testapi.ad6755.com
  // https://api.youshuyun.com
  let address = 'https://api.youshuyun.com', _data = data
  data.market_name = 'kuaiyingyong'
  data.app_type = 32
  data.token = await getToken();


  // 接口报错 死循环会一直调用 
  // if( data.token === ''){
  //   data.token = await fn_device()
  // }
  let device = await getDevice()
  header = Object.assign({
    'Content-Type': 'application/x-www-form-urlencoded',
    'version': '3.1.8',
    'appsystem': 'kuaiyingyong',
    'os': 0
  }, header, device)
  header.key = await getKey()
  header.sex_type = await fn_get_sex()
  header.Uid = await get_user_id()
  let device_info = await fn_device_get()

  let device_oaid = parseInt(device.platformVersionCode) >= 1060 ? await fn_device_oaid_get() : ''

  // let device_oaid = await fn_device_oaid_get()
  // prompt.showToast({message:'oaid-----------' + JSON.stringify(device_oaid) })

  // prompt.showToast({message:this.$app.$def.APPdata.is_call})
  let is_call = null;
  if(_this !== ''){
    // console.log('3434343434----------------------------')
    // console.log(_this.is_call == true)
    is_call = _this.is_call
  }

  
  device_info = (device_info === '' || device_info == '{}' ) ||  is_call == true
    ? await fn_device_getID(_this)
    : JSON.parse(device_info)
  

  // prompt.showToast({message:JSON.stringify(device_info)})

  // console.log('device_info = ' +device_info)

  // prompt.showDialog({
  //   message:'device_info获取 ======= ' +JSON.stringify(device_info),
  //   buttons:[{
  //     text:"确定"
  //   }]
  // })

  header.imei = device_info.device === '' ? '' : device_info.device
  header.mac = device_info.mac === '' ? '' : device_info.mac
  header.androidid = device_info.user === '' ? '' : device_info.user

  header.oaid = device_oaid === '' ? '' : device_oaid 

  header.os = 0

  header.brandname = device.brand
  header.modelname = device.model


  // data.token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vdGVzdGFwaS5hZDY3NTUuY29tL3FxX2xvZ2luIiwiaWF0IjoxNTcyMzM3MTA0LCJleHAiOjE1NzI0MjM1MDQsIm5iZiI6MTU3MjMzNzEwNCwianRpIjoiM2cwYUQ0aVJ6N2RkN0NZQSIsInN1YiI6MTA0N30.7Le5IXiAS9lDZmcTPJ0QtnQ7CxbErI-sBwWI_rsX7JI'
  let ret = await new Promise((resolve, reject) => {

    if (url === '/save_device_id') {
      data.Uid = data.only_code
      // prompt.showDialog({
      //   message: JSON.stringify(data) 
      // })

    }
    fetch
      .fetch({
        url: address + url,
        responseType: 'json',
        header: header,
        method: 'POST',
        data: data
      })
      .then(
        response => {
          // if (url === '/save_device_id') {
          //   prompt.showDialog({
          //     message: response.data.code
          //   })
          // }
          if (response.data.code != 200) {
            prompt.showDialog({
              title: '异常接口',
              message: url + '  code:' + response.data.code,
              buttons: [
                {
                  text: '确定',
                  color: '#333'
                }
              ],
              success: function (data) {
                console.log('handling callback')
              },
              cancel: function () {
                console.log('handling cancel')
              },
              fail: function (data, code) {
                console.log(`handling fail, code = ${code}`)
              }
            })
            return false
          }

          if(response.data.code == 200 && response.data.data.code == 401){
            storage.set({
              key: "token",
              value: "",
              success: function () {
                prompt.showDialog({
                  title: '提示',
                  message: '网络开小差了~~是否刷新页面',
                  buttons: [
                    {
                      text: '确定',
                      color: '#000'
                    },
                  ],
                  success: function (data) {
                    if (data.index == 0) {
                      router.replace({
                        uri: '/Tabbar'
                      })
                    }
                  }
                })
                fn_get_devic()
              }
            })

          }
          resolve(response.data.data)
        },
        err => {
          reject(err)
          if(err.code == 1000){
            prompt.showToast({
              message:'数据请求失败，请确定网络状态'
            })
          }
          
        }
      )
      .catch(error => {
        console.log(`handling fail, errMsg = ${error.data}`)
        console.log(`handling fail, errCode = ${error.code}`)
      })
      
  })
  // console.log(ret.data)
  if (ret.data.token != undefined) {
    console.log('存储')
    let aa = await setToken(ret.data.token)
  }

  return ret
}

function get_user_id(){
  return new Promise((resolve)=>{
    device.getUserId({
      success:function(res){
        // 读取文件存贮的uid  
        file.readText({
          uri: 'internal://files/youshuyun/uid.txt',
          success: function(data) {
            // 文件存贮的uid和获取到的uid是否一致
            //res.userId == data.text
            if(res.userId == data.text){
              resolve(res.userId)
            }else{
              // 文件存贮的uid和获取到的uid不一致上报接口
              let request_data = {old_code:data.text,new_code:res.userId}
              api.api('' , '/update_kuaicode',request_data).then(ret=>{
                if(ret.code == 1){
                  // 上报成功  删除原来的文件
                  file.delete({
                    uri: 'internal://files/youshuyun/uid.txt',
                    success:function(){
                      // 重新在写入一个
                      file.writeText({
                        uri: 'internal://files/youshuyun/uid.txt',
                        text: res.userId,
                        success: function() {
                          resolve(res.userId)
                        },
                        fail: function(data, code) {
                          resolve('')
                        }
                      })
                    }
                  })
                }
              })
            }
          },
          fail: function(data, code) {
            // 并没有文件记录uid  所以直接写一个进去
            if(code == 301){
              file.writeText({
                uri: 'internal://files/youshuyun/uid.txt',
                text: res.userId,
                success: function() {
                  resolve(res.userId)
                },
                fail: function(data, code) {
                  resolve('')
                }
              })
            }
          }

        })
        resolve(res.userId)
      },
      fail: function() {
        resolve('')
      }
    })
  })
}

function get_mobile(){
  return new Promise((resolve, reject)=>{
    storage.get({
      key:'mobile',
      success:(res)=>{
        resolve(res)
      }
    })
  })
}


async function fn_get_devic() {

  let uid = await get_user_id()
  let code = md5(uid + new Date())
  let device = await getDevice()
  let mobile = await get_mobile() ? await get_mobile(): ''
  let data = {
    'only_code': uid,
    'deviceCode': code,
    'mobile':mobile
  }
  let header = {}
  header.key = await getKey()
  header.brandname = device.brand
  header.modelname = device.model
  header.Uid = uid
  header.mobile = mobile
  return fn_save_device_id(data, header)
}
// 生成新的用户
function fn_save_device_id(data, header) {
  api( '' , '/save_device_id', data, header)
    .then(res => {
      if (res.code == 1) {
        storage.set({
          key: 'token',
          value: res.data.token
        })
      }
    })
}

 // 获取是否登录
function login() {
  return new Promise((resolve, reject) => {
    storage.get({
      key: 'token',
      success: function (res) {
        resolve(res)
      }
    })
  })
}

function fn_get_sex(){
  let that = this
  return new Promise ((resolve)=>{
      storage.get({
          key:"preferences",
          success:function(res){
              if(res){
                  resolve(parseInt(res)+1)
              }else{
                resolve(2)
              }
          }
      })
  })
}

function fn_give_time(){
  let date = new Date()
  return ""+ date.getFullYear() +date.getMonth() + date.getDay()
}



export default {
  api,
  fn_get_devic,
  get_user_id,
  getDevice,
  login,
  fn_give_time

}
